import axios from 'axios'
import { getToken } from './auth'

// 创建 axios 实例
const service = axios.create({
    baseURL: 'https://api.dixinwangluokeji.com', // 基础URL
    timeout: 15000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = getToken()
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        // 这里可以根据后端的响应结构进行调整
        return res
    },
    error => {
        // 这里可以统一处理错误
        return Promise.reject(error)
    }
)

// 封装 GET 请求
export function get(url, params, headers = {}) {
    return service({
        url,
        method: 'get',
        params,
        headers: {
            'Content-Type': 'application/json',
            ...headers
        }
    })
}

// 封装 POST 请求
export function post(url, data, headers = {}) {
    return service({
        url,
        method: 'post',
        data,
        headers: {
            'Content-Type': 'application/json',
            ...headers
        }
    })
}

// 封装 PUT 请求
export function put(url, data, headers = {}) {
    return service({
        url,
        method: 'put',
        data,
        headers: {
            'Content-Type': 'application/json',
            ...headers
        }
    })
}

// 封装 DELETE 请求
export function deletes(url, data, headers = {}) {
    return service({
        url,
        method: 'delete',
        data,
        headers: {
            'Content-Type': 'application/json',
            ...headers
        }
    })
}

// 封装 PATCH 请求
export function patch(url, data, headers = {}) {
    return service({
        url,
        method: 'patch',
        data,
        headers: {
            'Content-Type': 'application/json',
            ...headers
        }
    })
}

export default service